﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core.Entities;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
using Serilog.Core;

namespace Glorysoft.EAP.Core
{
    public class FTPHelper
    {
        protected readonly static Logger EAPlogger = XfwContext.LogManager.EapLogger;      

        public static void FtpFileDownload(string savePath, string ftpServerPath, string ftpUserID, string ftpPassword)
        {

            string ftpUser = ftpUserID;
            string ftpPwd = ftpPassword;

            Uri uri = new Uri(ftpServerPath);
            string FileName = Path.GetFullPath(savePath) + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(uri.LocalPath);
            string saveFilePath = FileName;

            FileStream outputStream = null;
            FtpWebResponse response = null;
            FtpWebRequest reqFTP;

            try
            {
                outputStream = new FileStream(saveFilePath, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerPath));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                reqFTP.Timeout = 3000;
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
                response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                int bufferSize = 2048;
                int readCount;
                int ftpFileReadSize = 0;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    ftpFileReadSize += readCount;
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {

                if (outputStream != null)
                {
                    outputStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }

        /// <summary>
        /// 2.遍历单个文件夹下的所有文件的名称，存到一个数组中。
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <returns></returns>

        public static string[] GetFtpList(string ftpPath, string name, string type, string userName, string password)
        {
            WebResponse webresp = null;
            StreamReader ftpFileListReader = null;
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath + name));
                ftpRequest.Method = type;
                ftpRequest.Credentials = new NetworkCredential(userName, password);
                webresp = ftpRequest.GetResponse();
                ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            StringBuilder str = new StringBuilder();

            if (ftpFileListReader != null)
            {
                string line = ftpFileListReader.ReadLine();
                while (line != null)
                {
                    str.Append(line);
                    str.Append("\n");
                    line = ftpFileListReader.ReadLine();
                }
                ftpFileListReader.Close();
            }
            webresp.Close();
            string[] ftpFileList = str.ToString().Split('\n');
            return ftpFileList;
        }
        /// <summary>
        /// 3.递归文件夹，获取文件夹及子文件夹中的文件
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="name"></param>
        /// <param name="downFilePath"></param>
        public static void DownFolder(string ftpPath, string name, string downFilePath, string userName, string password,DateTime? updateTime,bool isDel=false)
        {
            //string name = Path.GetFileName(ftpPath);
            string downloadDir = downFilePath + name;
            string ftpdir = ftpPath + name;
            string[] fullname = GetFtpList(ftpPath, name, WebRequestMethods.Ftp.ListDirectoryDetails, userName, password);

            string[] onlyname = GetFtpList(ftpPath, name, WebRequestMethods.Ftp.ListDirectory, userName, password);

           
            if (!Directory.Exists(downloadDir))
            {
                Directory.CreateDirectory(downloadDir);
            }
            
            int count = -1;
            foreach (string names in fullname)
            {
                count++;
                var item = names;
                //判断是否具有文件夹标识<DIR>  //linux下第一个字母d表示是文件夹
                if (names.Contains("<DIR>"))
                {
                    string olname = names.Split(new string[] { "<DIR>" },
                    StringSplitOptions.None)[1].Trim();
                    //"//" + olname,
                    DownFolder(ftpdir, "//" + onlyname, downloadDir, userName, password, updateTime);
                }

                else if (names != "" && names.Trim().Substring(0, 1).ToUpper() == "D")
                {

                    string olname = name;
                    //string olname = name.Substring(54).Trim();
                    if (olname != "." && olname != "..")
                    {
                        olname = onlyname[count];
                        if (olname.IndexOf("/") > 0)
                        {
                            olname = olname.Substring(olname.LastIndexOf("/") + 1);
                        }
                        //DownFolder(ftpdir, "//" + onlyname[count], downloadDir, userName, password);
                        DownFolder(ftpdir, "//" + olname, downloadDir, userName, password, updateTime);
                    }
                }
                else
                {
                    foreach (string onlynames in onlyname)
                    {
                        if (onlynames == "" || onlynames == " " || names == "")
                        {
                            break;
                        }
                        else
                        {
                            var temp = onlynames;
                            if (onlynames.IndexOf("/") > 0)
                            {
                                temp = onlynames.Substring(onlynames.LastIndexOf("/") + 1);
                            }
                            if (names.Contains(temp))
                            {                               
                                string ftppath = ftpPath + name + "/" +
                                temp;
                                DateTime filedate= GetFileModifyDateTime(ftppath, userName, password);
                                if (updateTime != null)
                                {
                                    EAPlogger.Debug($"DownFile>updateTime:{updateTime};filedate:{filedate}");
                                    //增加文件日期判断
                                    if (filedate> updateTime)
                                    {
                                        DownFile(downloadDir + "/" + temp, ftppath, userName, password);
                                    }
                                }
                                else
                                {
                                    //DownFile(downloadDir + "/" + temp, ftppath, userName, password);
                                }
                                if (isDel)
                                {
                                    Delete(ftpPath + name + "/" +
                                    temp, userName, password);
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 1.下载单个文件
        /// </summary>
        /// <param name="downFilePath"></param>
        /// <param name="ftpPath"></param>
        public static void DownFile(string downFilePath, string ftpPath, string userName, string password)
        {

            //FileMode常数确定如何打开或创建文件，指定操作系统应创建新文件。
            //FileMode.Create如果文件已存在，它将被改写。
            FileStream outputStream = new FileStream(downFilePath, FileMode.Create);
            FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
            //设置要发送到FTP服务器的命令
            downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            downRequest.Credentials = new NetworkCredential(userName, password);
            downRequest.KeepAlive = true;
            FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long c1 = response.ContentLength;
            int bufferSize = 65536;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();

        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void Delete(string fileName,string account,string pwd)
        {
            try
            {
                string uri =  fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

                reqFTP.Credentials = new NetworkCredential(account, pwd);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
                //Buffer.Log(string.Format("Ftp文件{1}删除成功！", DateTime.Now.ToString(), fileName));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static DateTime GetFileModifyDateTime(string ftpPath, string ftpUserID, string ftpPwd)

        {
            FtpWebRequest reqFTP = null;
            try
            {               

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));

                reqFTP.UseBinary = true;
                //reqFTP.UsePassive = false;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPwd);

                reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                DateTime dt = response.LastModified;

                response.Close();
                response = null;
                reqFTP = null;
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 上传文件到远程ftp
        /// </summary>
        /// <param name="ftpPath">ftp上的文件路径</param>
        /// <param name="path">本地的文件目录</param>
        /// <param name="id">文件名</param>
        /// <returns></returns>
        public static bool UploadFile(string ftpPath, string path,string FTPUSERNAME,string FTPPASSWORD)
        {
            string erroinfo = "";
            FileInfo f = new FileInfo(path);                             
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
            reqFtp.KeepAlive = false;
            reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
            reqFtp.ContentLength = f.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = f.OpenRead();
            try
            {
                Stream strm = reqFtp.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
                erroinfo = "完成";
                return true;
            }
            catch (Exception ex)
            {
                erroinfo = string.Format("因{0},无法完成上传", ex.Message);
                return false;
            }
        }
    }
}
